package com.qfedu.controller;

import com.qfedu.common.JsonResult;
import com.qfedu.entity.User;
import com.qfedu.service.UserService;
import com.qfedu.utils.StrUtils;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.constraints.Size;
import java.util.Iterator;

/**
 * @Author 刘浩
 * @Date 2020/8/18 21:59
 */
@Controller
@Validated//如果想要在方法的参数上面使用验证注解必须写这个注解
public class LoginController {
    @Autowired
    private UserService userService;
    @RequestMapping("/login.do")
    @ResponseBody
    public JsonResult login(@NotEmpty(message = "{name.empty}") String bankCode, @Size(min = 1, max = 10,message ="密码错误 不符合要求" ) String password, HttpSession session) {
        User user = userService.login(bankCode, password);
        session.setAttribute(StrUtils.LOGIN_USER, user);
        JsonResult jsonResult = new JsonResult(1, null);
        return jsonResult;
    }

//    //现在报了一个异常ConstraintViolationException
//    //处理这个异常 捕捉ConstraintViolationException
//    @ExceptionHandler(ConstraintViolationException.class)
//    @ResponseBody
//    public JsonResult constraintViolationException(ConstraintViolationException ex) {
//        // 验证不通过的信息
//        Iterator<ConstraintViolation<?>>
//                iterator = ex.getConstraintViolations().iterator();
//        String message = null;
//        if (iterator.hasNext()) {
//            message = iterator.next().getMessage();
//            System.out.println(message);
//        }
//        return new JsonResult(0, message);
//    }
//
//    // 处理那些没有预料到的异常
//    @ExceptionHandler
//    @ResponseBody
//    public JsonResult commonException(Exception ex) {
//        return new JsonResult(0, ex.getMessage());
//    }
}
